/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.component.message.impl.base;

import android.support.annotation.Nullable;

import com.xuexiang.xdlink.component.message.IResponseMessage;
import com.xuexiang.xdlink.logs.DCFLog;
import com.xuexiang.xdlink.util.ConvertTools;

/**
 * 基础的响应消息实体
 *
 * @author xuexiang
 * @since 2018/8/30 下午11:19
 */
public abstract class XResponseMessage<T> extends XMessage implements IResponseMessage {

    /**
     * 消息携带的有效数据
     */
    private T mData;

    @Override
    @Nullable
    public XResponseMessage<T> resolve(byte[] data) {
        if (verifyMessage(data)) { //验证消息是否正确
            fillMessageData(data); //填充数据
            setMessageData(transformMessageData(getContentData())); //对contentData字段数据进行转化
            return this;
        }
        DCFLog.e("message data resolve verify failed: " + ConvertTools.bytes2HexString(data));
        return null; //解析不成功直接返回null
    }

    /**
     * @return 初始化响应请求的功能码
     */
    protected abstract byte initFuncCode();

    /**
     * 将contentData字段的数据转化为需要的、有效的数据
     *
     * @param contentData
     * @return
     */
    protected abstract T transformMessageData(byte[] contentData);


    /**
     * @return 是否是有效的返回消息【消息类型正确】
     */
    public boolean isValidMessage() {
        return initFuncCode() == getFuncCode();
    }

    /**
     * @return 是否是成功的返回消息
     */
    public boolean isMessageSuccess() {
        return isValidMessage() && getRetCode() == (byte) 0;
    }

    /**
     * @return 获取消息携带的有效数据
     */
    public T getMessageData() {
        return mData;
    }

    /**
     * 设置携带的有效数据
     *
     * @param data
     * @return
     */
    public XResponseMessage<T> setMessageData(T data) {
        mData = data;
        return this;
    }
}
